//
//  BIgeyesRequest.m
//  RequestDemo
//
//  Created by 红沙尘 on 17/4/20.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "BIgeyesRequest.h"
#import "AFHTTPSessionManager.h"
#import "HSCLog.h"

@implementation BIgeyesRequest

+(void)requestWithApi:(NSString *)url
                param:(NSMutableDictionary *)param
          thenSuccess:(void (^)(NSDictionary *responseObject))success
                 fail:(void (^)(void))fail
{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json", @"text/javascript",@"application/json",@"text/html",@"text/plain", nil];
//    manager.requestSerializer.timeoutInterval = 100;
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误
//    manager.securityPolicy.allowInvalidCertificates = YES;
//    manager.securityPolicy.validatesDomainName = NO;//另外还要注意判断传入 传出的是不是JSON数据
    
    NSMutableDictionary *args = [self apiparam:param];
    
    NSLog(@"url = %@",url);
    NSLog(@"param = %@",args);
    
    NSLog(@"url = %@",url);
    NSLog(@"param = %@",args);
    
    [manager POST:url parameters:args progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = responseObject;
        
        [HSCLog saveDebugWithURL:url param:args result:dict];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"dict = %@",dict);
            //            NSLog(@"result = %@",result);
            !success ? : success(dict);
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        
        NSString *desc = [NSString stringWithFormat:@"%@",error.localizedDescription];
        NSString *reason = [NSString stringWithFormat:@"%@",error.localizedFailureReason];
        NSString *code = [NSString stringWithFormat:@"%d",(int)error.code];
        
        NSDictionary *dict = @{@"desc":desc,
                               @"reason":reason,
                               @"code":code};
        
        [HSCLog saveDebugWithURL:url param:args result:dict];
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            fail(error);
        });
    }];
    
    
}

+ (NSMutableDictionary *)apiparam:(NSMutableDictionary *)param {
    
    NSMutableDictionary *args = @{}.mutableCopy;
    
    args[@"apiVersion"] = @"1.0";
    args[@"params"]     = param;
    
    return args;
}

    

@end











